import axios from 'axios'
import { useUserStore } from '@/store'
import router from '@/router'
import { ElMessage } from 'element-plus' // 修复：导入ElMessage

const service = axios.create({
  baseURL: '',
  timeout: 10000
})

service.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    // 如需token验证，添加如下代码
    if (userStore.isLogin) {
      config.headers.Authorization = userStore.userInfo.token || ''
    }
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

let isTokenExpiredMessageVisible = false;

service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code !== 0) {
      if ([401].includes(res.code)) {
        if (!isTokenExpiredMessageVisible) {
          isTokenExpiredMessageVisible = true;
          ElMessage({
            message: '登录状态已过期，请重新登录',
            type: 'error',
            duration: 5 * 1000,
            onClose: () => {
              isTokenExpiredMessageVisible = false;
            }
          });
          const userStore = useUserStore()
          userStore.logout()
          router.push('/login');
        }
      }
      return Promise.reject(new Error(res.msg || 'Error'));
    }
    return res;
  },
  error => {
    console.error('Response error:', error);
    let message = '网络错误';
    if (error.response && error.response.data && error.response.data.msg) {
      message = error.response.data.msg;
    } else if (error.msg) {
      message = error.msg;
    }
    ElMessage.error(message);
    return Promise.reject(error);
  }
);

export default service